/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Datatypes.DataCompra;
import Datatypes.DataJuego;
import Datatypes.PDate;
import Fabricas.Factory;
import Interfaces.*;
import java.awt.Dimension;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author chonabook
 */
public class JIFComprarJuego extends javax.swing.JInternalFrame {

    private Factory f = null;
    private IJuego ij = null;
    private IPerfil ip = null;
    private IComentario ic = null;
    /**
     * Creates new form JIFComprarJuego
     */
    public JIFComprarJuego(Factory f) throws Exception{
        
        this.f = f;
        this.ij = f.getIJuego();
        this.ip = f.getIPerfil();
               
        initComponents();
        cargarJuegos();
        cargarClientes();
        this.jBtnAceptar.setEnabled(false);
    }
    
    private void centrarVentana(){
        
        Dimension desktopSize = JIFInicial.getDPInicioDimension();
        Dimension jInternalFrameSize = this.getSize();
        this.setLocation((desktopSize.width - jInternalFrameSize.width)/2,
                                   (desktopSize.height- jInternalFrameSize.height)/2);
        //setLocation(55, 55);
        
    }
    
    //public void cargar
    private void cargarJuegos() throws Exception {
        
        List<DataJuego> listaJ = ij.listarJuegosAprobados();
        DefaultTableModel tm = (DefaultTableModel) this.jTblJuegos.getModel();
        int rows = 0;
        
        for (DataJuego dj : listaJ) {

            tm.addRow(new Object[rows]);
            tm.setValueAt(dj.getNombre(), rows, 0);
            tm.setValueAt(dj.getPrecio(), rows, 1);
            rows++;
        }
        
        
    }
    
    private void cargarClientes()throws Exception{
        
        List<String> clientes = this.ip.listarClientes();
        int i = 0;
        int largo = clientes.size();
        for(i=0; i<largo; i++){
            
            this.jCBNickCliente.addItem(clientes.get(i));
            
        }
        
    }
    
    public void setBloquearComponentes(){
    
        jCBNickCliente.setEnabled(!isEnabled());
        jSpinnerMes.setEnabled(!isEnabled());
        
    
    }
    
    public void setDesbloquearComponentes(){
        
        jCBNickCliente.setEnabled(true);
        jSpinnerMes.setEnabled(true);
        
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTblJuegos = new javax.swing.JTable();
        jBtnAceptar = new javax.swing.JButton();
        jBtnCancelar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLblTablaJuegos = new javax.swing.JLabel();
        jLblNickComprador = new javax.swing.JLabel();
        jCBNickCliente = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jSpinnerMes = new javax.swing.JSpinner();
        jScrollPane2 = new javax.swing.JScrollPane();
        JTADescripcion = new javax.swing.JTextArea();
        jLblTablaJuegos1 = new javax.swing.JLabel();

        setClosable(true);
        setResizable(true);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jTblJuegos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "<html><b>Nombre</b></html>", "<html><b>Precio</b></html>"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTblJuegos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTblJuegos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTblJuegosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTblJuegos);

        jBtnAceptar.setText("Aceptar");
        jBtnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnAceptarActionPerformed(evt);
            }
        });

        jBtnCancelar.setText("Cancelar");
        jBtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnCancelarActionPerformed(evt);
            }
        });

        jLblTablaJuegos.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLblTablaJuegos.setText("Listado de Juegos:");

        jLblNickComprador.setText("Nick del Cliente:");

        jCBNickCliente.setModel(new javax.swing.DefaultComboBoxModel(new String[] {}));

        jLabel1.setText("Fecha de Compra:");

        jSpinnerMes.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), new java.util.Date(-2208975316000L), new java.util.Date(), java.util.Calendar.YEAR));

        jScrollPane2.setAutoscrolls(true);

        JTADescripcion.setEditable(false);
        JTADescripcion.setColumns(20);
        JTADescripcion.setRows(5);
        jScrollPane2.setViewportView(JTADescripcion);

        jLblTablaJuegos1.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLblTablaJuegos1.setText("Descripción");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 588, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jBtnCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jBtnAceptar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLblTablaJuegos)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLblNickComprador)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jCBNickCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel1)
                                        .addGap(18, 18, 18)
                                        .addComponent(jSpinnerMes, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator1))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLblTablaJuegos1)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jScrollPane2))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLblTablaJuegos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jBtnAceptar)
                        .addGap(18, 18, 18)
                        .addComponent(jBtnCancelar)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLblTablaJuegos1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLblNickComprador)
                            .addComponent(jCBNickCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)
                            .addComponent(jSpinnerMes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(20, 20, 20))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    public String getSelectedNombre(int row){
        
        DefaultTableModel tm = (DefaultTableModel) this.jTblJuegos.getModel();
        String nombre_juego = tm.getValueAt(row, 0).toString();
        return nombre_juego;
        
    }
    
    private void jBtnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnAceptarActionPerformed
        
        int row = this.jTblJuegos.getSelectedRow();
        String nombreJuego = getSelectedNombre(row);
        String cliente = this.jCBNickCliente.getSelectedItem().toString();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date fechax = (Date) this.jSpinnerMes.getValue();
        String fecha = format.format(fechax).toString();
        System.out.println(fecha);
        PDate fechaCompra = null;
        
        try{
        
            fechaCompra = new PDate(fecha);
            
        }
        
        catch(Exception e){

            JOptionPane.showMessageDialog(this, e.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE, null);

        }
        //String f = Fecha.getDay()+Fecha.getMonth()+Fecha.
        DataCompra Dcompra = new DataCompra(fechaCompra, cliente, nombreJuego);
        int retorno = JOptionPane.showConfirmDialog(null, "<html>Confirme datos de compra<li><li><b>Juego:</b> "+nombreJuego+"<li><b>Cliente:</b> "+cliente+ "<li><b>Fecha:</b> "+fechaCompra.getString()+"</html>","Confirmar " ,JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        
        if(retorno == JOptionPane.YES_OPTION){
            
            
            
            try{
                
                ij.registrarCompra(Dcompra);
                
                JOptionPane.showMessageDialog(null, "Compra agregada con éxito", "Success", JOptionPane.PLAIN_MESSAGE);
            
            }
            catch(Exception e){
                
                JOptionPane.showMessageDialog(this, "Este cliente ya compro este juego.", "Error!", JOptionPane.ERROR_MESSAGE, null);
                
            }
            this.dispose();
            JIFInicial.BloquearJFInicial();
            
        }
        else if(retorno == JOptionPane.NO_OPTION){
            
            this.dispose();
            JIFInicial.BloquearJFInicial();
            
        }      
        
    }//GEN-LAST:event_jBtnAceptarActionPerformed

    private void jBtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCancelarActionPerformed

        this.dispose();
        JIFInicial.BloquearJFInicial();
        
    }//GEN-LAST:event_jBtnCancelarActionPerformed

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing

        JIFInicial.BloquearJFInicial();
        
    }//GEN-LAST:event_formInternalFrameClosing

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened

        centrarVentana();
        
    }//GEN-LAST:event_formInternalFrameOpened

    private void jTblJuegosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTblJuegosMouseClicked
        
       int row = jTblJuegos.rowAtPoint(evt.getPoint());
       int col = jTblJuegos.columnAtPoint(evt.getPoint());
        if (row >= 0 && col >= 0) {
           try {
               Integer indice = this.jTblJuegos.getSelectedRow();
               
               DataJuego dj = ij.elegirJuego(jTblJuegos.getValueAt(indice, 0).toString());
               this.JTADescripcion.setText(dj.getDescripcion());
               setDesbloquearComponentes();
               this.jBtnAceptar.setEnabled(true);
           } catch (Exception e) {
               
               JOptionPane.showMessageDialog(this, e.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE, null);
               
           }
            
        }
        
    }//GEN-LAST:event_jTblJuegosMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea JTADescripcion;
    private javax.swing.JButton jBtnAceptar;
    private javax.swing.JButton jBtnCancelar;
    private javax.swing.JComboBox jCBNickCliente;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLblNickComprador;
    private javax.swing.JLabel jLblTablaJuegos;
    private javax.swing.JLabel jLblTablaJuegos1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSpinner jSpinnerMes;
    private javax.swing.JTable jTblJuegos;
    // End of variables declaration//GEN-END:variables

  
}

